<template>
  <van-search
    v-model="key"
    show-action
    label="商品"
    background="#ff623a"
    placeholder="请输入搜索关键词"
    @search="onSearch"
  >
    <template #action>
      <div @click="onSearch">搜索</div>
    </template>
  </van-search>
  <div>
    <h3>历史记录</h3>
    <div v-if="searchHis.length === 0">暂无搜索记录</div>
    <div v-for="his in searchHis" :key="his">
      {{ his }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
const key = ref("");
// searchHis 缓存搜索历史记录
let searchHis = localStorage.getItem("searchHis")
  ? JSON.parse(localStorage.getItem("searchHis") as string)
  : [];
const onSearch = () => {
  // 存这个搜索历史记录
  searchHis.unshift(key.value);
  // 数组去重
  searchHis = [...new Set(searchHis)];
  if (searchHis.length > 10) {
    searchHis.pop();
  }
  localStorage.setItem("searchHis", JSON.stringify(searchHis));
  router.push({
    path: "/result",
    query: {
      key: key.value,
    },
  });
};
</script>

<style scoped></style>
